<template>
  <div v-if="pageStatus === 1">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form ref="queryFormRef" :inline="true" :model="paramsData" class="-mb-10px" label-width="auto">
        <el-form-item label="车牌号" prop="cardNo">
          <el-input v-model="paramsData.cardNo" class="!w-280px" clearable placeholder="请输入车牌号"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="厂牌型号" prop="labelType">
          <el-input v-model="paramsData.labelType" class="!w-280px" clearable placeholder="请输入厂牌型号"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="车辆品牌" prop="carBrand">
          <el-input v-model="paramsData.carBrand" class="!w-280px" clearable placeholder="请输入车辆品牌"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="核定乘员数" prop="maxOccupants">
          <el-input-number v-model="paramsData.maxOccupants" controls-position="right"  class="!w-280px" clearable placeholder="请输入核定乘员数"
            @keyup.enter="handleQuery" />
        </el-form-item>        
        <el-form-item label="车型" prop="cardType">
          <el-select v-model="paramsData.cardType" filterable class="!w-280px" clearable placeholder="请选择车型">
            <el-option v-for="item in carTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
  
        <el-form-item label="所属部门" prop="departmentId">
          <el-tree-select
            v-model="paramsData.departmentId"
            class="!w-280px"
            :data="deptTree"
            filterable
            clearable
            :props="defaultProps"
            check-strictly
            default-expand-all
            placeholder="请选择所属部门"
            value-key="deptId"
          />
        </el-form-item>
      
        <el-form-item label="运行状态" prop="runId">
          <el-select v-model="paramsData.runId" filterable class="!w-280px" clearable placeholder="请选择运行状态">
            <el-option v-for="item in runList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="运营状态" prop="operateId">
          <el-select v-model="paramsData.operateId" filterable class="!w-280px" clearable placeholder="请选择运营状态">
            <el-option v-for="item in operateList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button v-hasPermi="['wise:project:query']" @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
          <el-button v-hasPermi="['wise:project:create']" plain type="primary" @click="openForm(1)">
            <Icon class="mr-5px" icon="ep:plus" />
            新增
          </el-button>
          <el-button v-hasPermi="['wise:project:export']" :loading="exportLoading" plain type="success"
            @click="handleExport">
            <Icon class="mr-5px" icon="ep:download" />
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <ContentWrap>
      <el-table v-loading="loading" :data="tableData" @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="30" />
        <template v-for="item in tableColumn" :key="item.prop">
          <el-table-column
            :width="item.width"
            :align="item.align ? item.align : 'center'" 
            :label="item.label"
            :prop="item.prop"
          >
            <template #default="scope">
              <div v-if="item.prop === 'departmentId'">
                {{ findDeptNameById(deptTree, scope.row.departmentId) || '-' }}
              </div>
              <div v-else-if="item.prop == 'isNewEnergy'">
                <span type="success" v-if="scope.row.isNewEnergy">是</span>
                <span type="error" v-else>否</span>
              </div>
              <div v-else-if="item.prop == 'runId'">
                <el-tag type="success" v-if="scope.row.operateId == 1">使用</el-tag>
                <el-tag type="error" v-else-if="scope.row.operateId == 2">停用</el-tag>
                <el-tag type="info" v-else-if="scope.row.operateId == 3">闲置</el-tag>
                <el-tag type="warning" v-else-if="scope.row.operateId == 4">维护</el-tag>
                <span v-else>-</span>
              </div>
              <div v-else-if="item.prop == 'operateId'">
                <el-tag type="success" v-if="scope.row.operateId == 1">可使用</el-tag>
                <el-tag type="error" v-else-if="scope.row.operateId == 2">故障</el-tag>
                <el-tag type="warning" v-else-if="scope.row.operateId == 3">维护</el-tag>
                <span v-else>-</span>
              </div>
              <div v-else-if="item.prop == 'createTime'">
                <p>创建时间：{{ scope.row.createTime ? formatDate(scope.row.createTime) : '-' }}</p>
                <p>更新时间：{{ scope.row.updateTime ? formatDate(scope.row.updateTime) : '-' }}</p>
              </div>
              <div v-else-if="item.prop == 'creator'">
                <p>创建：{{ scope.row.creator ? scope.row.creator : '-' }}</p>
                <p>更新：{{ scope.row.updater ? scope.row.updater : '-' }}</p>
              </div>
              <div v-else>
                {{ scope.row[item.prop] || '-' }}
              </div>
            </template>
          </el-table-column>
        </template>
  
        <el-table-column :width="200" align="center" label="操作">
          <template #default="scope">
            <el-button v-hasPermi="['wise:employee:update']" link type="primary" @click="openForm(2, scope.row.id)">
              编辑
            </el-button>
            <el-button v-hasPermi="['wise:employee:delete']" link type="danger" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
  
      </el-table>
  
  
      <!-- 分页 -->
      <Pagination v-model:limit="paramsData.pageSize" v-model:page="paramsData.pageNo" :total="total" @pagination="getList" />
    </ContentWrap>
  </div>
  <VehicleForm v-else ref="formRef" />
</template>
<script setup>
  import {ref,reactive} from "vue"
  import { defaultProps, handleTree } from '@/utils/tree'
  import * as DeptApi from '@/api/system/dept'
  import { formatDate } from '@/utils/formatTime'
  import { runList, operateList } from './jsonAndRules'
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import VehicleForm from './vehicleForm.vue'
  const carTypeList = ref(getIntDictOptions(DICT_TYPE.CAR_TYPE)) // 卡片类型数据
  provide('carTypeList', carTypeList)
  const pageStatus = ref(1) // 1列表页  2新增编辑页
  const exportLoading = ref(false) // 导出的加载中
  const paramsData = reactive({
    cardNo: '', // 车牌号
    labelType: '', // 厂牌型号
    carBrand: '', // 车辆品牌
    maxOccupants: null, // 核定乘员数
    cardType: null, // 车型Id
    departmentId: '', // 责任部门
    runId: '', // 运行状态
    operateId: '', // 运营状态
    pageNum: 1,
    pageSize: 10,
    ids: [],
  })
  const formRef = ref(null) // 新增、编辑页
  const loading = ref(false) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const tableData = ref([
    {
      cardNo: '粤B12345',
      cardTypeName: '小型车',
      labelTypeName: '奔驰C级',
      carBrand: '奔驰',
      departmentId: 101,
      isNewEnergy: 0,
      maxOccupants: 5,
      operateId: 1,
      runId: 1,
      createTime: 1758187445000, 
      updateTime: 1748186445235, 
      creator: '张三（13887625983）',
      updater: '李四（13887625983）'
    },
  ]) // 列表的数据
  const tableColumn = ref([
    { prop: 'cardNo', label: '车牌号', align: 'center', },
    { prop: 'cardTypeName', label: '车型', align: 'center'},
    { prop: 'labelTypeName', label: '厂牌型号', align: 'center'},
    { prop: 'carBrand', label: '车辆品牌', align: 'center'},
    { prop: 'departmentId', label: '所属部门', align: 'center'},
    { prop: 'isNewEnergy', label: '是否新能源', align: 'center',},
    { prop: 'maxOccupants', label: '核定乘员人数', align: 'center', width: 140},
    { prop: 'operateId', label: '运营状态', align: 'center',},
    { prop: 'runId', label: '运行状态', align: 'center',},
    { prop: 'createTime', label: '时间', align: 'center', width: 260},
    { prop: 'creator', label: '人员', align: 'center', width: 220},
  ]) // 表格的列
  const getList = async () => {

  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    paramsData.pageNo = 1
    // getList()
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    paramsData.leaderName = ''
    queryFormRef.value.resetFields()
    handleQuery()
  }
  const goBack = () => {
    pageStatus.value = 1
    // getList()
  }
  provide('goBack', goBack)
  const openForm = (id) => {
    pageStatus.value = 2
    nextTick(() => {
      formRef.value.init(id)
    })
  }
  const handleExport = async () => {
    if(selectIds.value.length > 0){
      paramsData.ids = selectIds.value
    }
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await ProjectApi.exportProject(paramsData)
      download.excel(data, '车辆管理列表.xls')
    } catch {
    } finally {
      exportLoading.value = false
    }
  }
  onMounted( async () => {
    await getTree()
    await getList()
  })
  const deptTree = ref() // 树形结构
  provide('deptTree', deptTree)
  /** 获得部门树 */
  const getTree = async () => {
    deptTree.value = []
    const data = await DeptApi.getSimpleDeptList()
    deptTree.value = handleTree(data)
  }
  function findDeptNameById(tree, id) {
    let nodeName = '-'
    for (const node of tree) {
      if (node.id === id) {
        nodeName = node.name
      }
      if(nodeName !== '-'){
        return nodeName
      }
      if(node.children && node.children.length > 0){
        nodeName = findDeptNameById(node.children, id)
      }
    }
    return nodeName
  }
  provide('findDeptNameById', findDeptNameById)
</script>
<style lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
